import { Body, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Code, Repository, Between } from 'typeorm';
import { sign } from 'jsonwebtoken';
import { User } from './user.entity';
import * as dayjs from 'dayjs';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}
  async loginS(body: { user_name: string; password: string }) {
    console.log(body);
    const user = await this.userRepository.findOne({
      where: {
        user_name: body.user_name,
        password: body.password,
      },
    });

    if (user) {
      if (user.state === 0) {
        return {
          code: 400,
          type: 'error',
          msg: '该账号已经失效',
        };
      } else {
        const token = sign({ user_name: body.user_name }, 'react', {
          expiresIn: '7d', // 7天过期
        });

        return {
          code: 200,
          msg: '登录成功',
          type: 'success',
          token,
          user_name: body.user_name,
          permissionCode: [1, 2, 3, 4, 5, 6, 7, 8, 9], // 权限码
        };
      }
    } else {
      return {
        code: 400,
        type: 'error',
        msg: '用户名或密码错误',
      };
    }
  }
  async getUserList(query: any) {
    if (query.user_name) {
      const list = await this.userRepository.findOne({
        where: {
          user_name: query.user_name,
        },
      });
      if (list) {
        return {
          code: 200,
          list: [
            {
              ...list,
              create_at: dayjs(list.create_at).format('YYYY-MM-DD HH:mm:ss'),
            },
          ],
          total: 1,
          msg: '获取成功',
        };
      } else {
        return {
          code: 200,
          list: [],
          total: 0,
          msg: '获取成功',
        };
      }
    }
    const whereCondition: any = {}; // 先定义一个空对象

    if (query.state * 1 !== 2) {
      whereCondition.state = query.state;
    }
    if (query.is_admin * 1 !== 2) {
      whereCondition.is_admin = query.is_admin;
    }
    whereCondition.create_at = Between(query.startTime, query.endTime);
    const list = await this.userRepository.find({
      where: whereCondition,
    });
    return {
      code: 200,
      list: list.map((item) => {
        return {
          ...item,
          create_at: dayjs(item.create_at).format('YYYY-MM-DD HH:mm:ss'),
        };
      }),
      total: 0,
      msg: '获取成功',
    };
  }

  // 添加用户
  async addUser(body: {
    user_name: string;
    password: string;
    is_admin: number;
    state: number;
    permission: string;
  }) {
    const user = await this.userRepository.findOne({
      where: {
        user_name: body.user_name,
      },
    });
    if (user) {
      return {
        code: 400,
        type: 'error',
        msg: '用户名已存在',
      };
    } else {
      const user = new User();
      user.user_name = body.user_name;
      user.password = body.password;
      user.is_admin = body.is_admin;
      user.state = body.state ?? 0;
      user.permission = body.permission ?? null;
      await this.userRepository.save(user);
      return {
        code: 200,
        type: 'success',
        msg: '添加成功',
      };
    }
  }
  // 修改用户状态
  async setInvalidUsers(param: any) {
    const db = await this.userRepository.findOne({
      where: {
        id: param.id,
      },
    });
    db.state = Number(!db.state);
    await this.userRepository.save(db);
    return {
      code: 200,
      type: 'success',
      msg: '修改成功',
    };
  }

  // 删除用户
  async deleteUser(query: any) {
    console.log(query);
    const db = await this.userRepository.findOne({
      where: {
        id: query.id,
      },
    });
    await this.userRepository.remove(db);
    return {
      code: 200,
      type: 'success',
      msg: '删除成功',
    };
  }
}
